#include "io_connector.h"
#ifdef DUMP_MEMORY_LEAK
#include <vld.h>
#endif
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/bind.hpp>

void IoConnector::startConnect(unsigned int timeout, const tcp::endpoint& addr, ConnetionCallBack err,
	ConnetionCallBack connected)
{
	addr_ = addr;
	connectionTimer_.expires_at(boost::posix_time::second_clock::local_time() + 
		boost::posix_time::seconds(timeout));

	connectionTimer_.async_wait(boost::bind(&IoConnector::connectTimeOut, this, 
		boost::asio::placeholders::error));
	socket_.async_connect(addr, boost::bind(&IoConnector::onConnectionReturned, 
		this, boost::asio::placeholders::error)); 
	err_ = err;
	connected_ = connected;
}

void IoConnector::connectTimeOut(const boost::system::error_code& e)
{
	if(isConnected_)
	{
		return;
	}
	socket_.close();
	isTimeOut_ = true;
}

void IoConnector::onConnectionReturned(const boost::system::error_code& err)
{
	if(err)
	{
		err_(addr_, this, err);
		return;
	}
	if(isTimeOut_)
	{
		return;
	}
	isConnected_ = true;
	connected_(addr_, this, err);
	start();
}
